package com.cindata

import grails.transaction.Transactional

import java.time.Year

@Transactional
class DateUtilService
{

    static scope = "singleton"

    static int getYearMonth(Date dt)
    {
        Calendar cal = Calendar.getInstance()
        //设置时间
        cal.setTime(dt.getTime())
        //获取年份
        int year = cal.get(Calendar.YEAR)
        //获取月份
        int month = cal.get(Calendar.MONTH)
        //返回年份乘以100加上月份的值，因为月份最多2位数，所以年份乘以100可以获取一个唯一的年月数值
        return year * 100 + month

    }

    static boolean isSameYearMonth(Date dt1, Date dt2)
    {
        int d1 = getYearMonth(dt1)
        int d2 = getYearMonth(dt2)
        if (d1 == d2)
        {
            //年月相等
            return true
        }
        else
        {
            return false
        }
    }

    static String showCurrentYear()
    {
        int year = Year.now().getValue();
        if (year > 2017)
        {
            return ("-" + year)
        }
        else
        {
            return ""
        }
    }

    //由出生日期获得年龄
    static int getAge(Date birthDay) throws Exception
    {
        Calendar cal = Calendar.getInstance()
        int yearNow = cal.get(Calendar.YEAR)
        int monthNow = cal.get(Calendar.MONTH)
        int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH)
        cal.setTime(birthDay)

        int yearBirth = cal.get(Calendar.YEAR)
        int monthBirth = cal.get(Calendar.MONTH)
        int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH)

        int age = yearNow - yearBirth

        if (monthNow <= monthBirth)
        {
            if (monthNow == monthBirth)
            {
                if (dayOfMonthNow < dayOfMonthBirth)
                {
                    age--
                }
            }
            else
            {
                age--
            }
        }
        return age
    }

    //根据信用最新查询日期判断页面中是否可以再次查询
    static boolean isQuery(Date creditLatestQueryDate)
    {
        if (!creditLatestQueryDate)
        {
            return true
        }
        Calendar cal = Calendar.getInstance()
        cal.setTime(creditLatestQueryDate)
        cal.add(Calendar.DATE, 7)
        def queryDate = cal.getTimeInMillis()
        def nowDate = new Date().getTime()
        if (nowDate > queryDate)
        {
            return true
        }
        else
        {
            return false
        }
    }
}
